/*
 * @Description: http错误异常过滤器
 * @Author: Haor
 * @Date: 2022-04-06 10:37:20
 * @LastEditTime: 2022-05-06 17:09:25
 * @LastEditors: Haor
 */

import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common'
import { HttpResult } from '@libs/http.result'

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
	catch(exception: HttpException, host: ArgumentsHost) {
		console.log('<<<<<<<< 进入异常拦截器 >>>>>>>')
		const ctx = host.switchToHttp()
		const response = ctx.getResponse()
		const message = exception.message // 错误信息
		const errorResponseContent = HttpResult.serverError(+ctx.getRequest().headers.nonce, message) // 错误相应内容
		// 状态码
		const status = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR

		// 设置返回的状态码、请求头、发送错误信息
		response.status(status)
		response.header('Content-Type', 'application/json; charset=utf-8')
		response.send(errorResponseContent)
	}
}
